<template>
  <div class="article-detail">
    <a-card :bordered="false">
      <template #title>
        <div class="article-header">
          <h1>{{ article.title }}</h1>
          <div class="article-meta">
            <span class="author">作者：{{ article.author }}</span>
            <span class="time">发布时间：{{ formatDate(article.createTime) }}</span>
            <a-tag :color="article.status === 'published' ? 'green' : 'orange'">
              {{ article.status === 'published' ? '已发布' : '草稿' }}
            </a-tag>
          </div>
        </div>
      </template>

      <div class="article-content">
        {{ article.content }}
      </div>

      <template #actions>
        <a-space>
          <a-button @click="goBack">
            <template #icon><arrow-left-outlined /></template>
            返回列表
          </a-button>
          <a-button type="primary" @click="handleEdit" v-if="article.status === 'draft'">
            <template #icon><edit-outlined /></template>
            编辑
          </a-button>
        </a-space>
      </template>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, EditOutlined } from '@ant-design/icons-vue'
import { anyHttpClient } from '@/network'

interface ArticleItem {
  id: number
  title: string
  author: string
  content: string
  status: 'published' | 'draft'
  createTime: string
}

const route = useRoute()
const router = useRouter()
const article = ref<ArticleItem>({
  id: 0,
  title: '',
  author: '',
  content: '',
  status: 'draft',
  createTime: ''
})

const fetchArticleDetail = async () => {
  try {
    const response = await anyHttpClient.get(`/api/article/${route.params.id}`)
    // 响应拦截器已经处理了 ApiResponse 格式，直接使用 response.data
    if (response.data) {
      article.value = response.data
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    message.error('获取文章详情失败')
  }
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const goBack = () => {
  router.push('/article')
}

const handleEdit = () => {
  router.push(`/article/edit/${article.value.id}`)
}

onMounted(() => {
  fetchArticleDetail()
})
</script>

<style scoped>
.article-detail {
  padding: 24px;
}

.article-header {
  margin-bottom: 24px;
}

.article-header h1 {
  margin-bottom: 16px;
  font-size: 24px;
  font-weight: 500;
}

.article-meta {
  color: rgba(0, 0, 0, 0.45);
}

.article-meta span {
  margin-right: 16px;
}

.article-content {
  margin: 24px 0;
  line-height: 1.8;
  white-space: pre-wrap;
}
</style>